<template>
  <div class="department">
    <el-row>
      <el-col :span="24">
        <dynForm :info-form="infoForm" :search-tags="searchTags">
          <el-button
            v-btnPermission:add
            type="primary"
            icon="el-icon-search"
            @click="doSearch"
          >
            {{ $t("search") }}</el-button
            >
        </dynForm>
      </el-col>
    </el-row>
    <div class="table-buttons">
      <el-button
        v-btnPermission:add
        icon="el-icon-plus"
        type="primary"
        @click="switchHandle('add')"
      >{{ $t("add") }}</el-button
      >
      <!-- <el-button
        v-btnPermission:edit
        :disabled="UpdateDisabled"
        type="primary"
        icon="el-icon-edit"
        @click="switchHandle('modify')"
      >{{ $t("modify") }}</el-button
      >
      <el-button
        v-btnPermission:delete
        :disabled="DeleteDisabled"
        type="danger"
        icon="el-icon-delete"
        @click="switchHandle('del')"
      >{{ $t("delete") }}</el-button
      > -->
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-download"
        @click="switchHandle('download')"
      >{{ $t("downloadTemp") }}</el-button>
      <el-upload
        :action="baseApi + '/config/upload/submit?name=DepartmentList'"
        :headers="headers"
        :show-file-list="false"
        :on-success="uploadSuccess"
        class="upload-btn"
        style="display: inline-block"
        accept=".xlsx"
        @on-error="importFail"
      >
        <el-button
          v-btnPermission:add
          type="primary"
          icon="el-icon-upload"
        >{{ $t("import") }}</el-button
        >
      </el-upload>
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-upload"
        @click="switchHandle('export')"
      >{{ $t("export") }}</el-button
      >
    </div>
    <!-- 主体部分 -->
    <el-card class="box-card" shadow="never">
      <!-- 表单部分 -->
      <el-row>
        <!-- <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        /> -->
        <el-table
          :data="tableData"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :default-expand-all="true"
          :header-cell-style="{ background: '#F2F6FC', color: '#606266' }"
          style="width: 100%"
          row-key="id"
          tooltip-effect="dark"
          border>
          <el-table-column
            :label="$t('deptName')"
            prop="name"
            header-align="center"
          />
          <el-table-column
            :label="$t('departmentCategory')"
            prop="category"
            align="center"
            header-align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ $t(scope.row.category) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('description')"
            prop="description"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            :label="$t('creator')"
            prop="creator"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            :label="$t('createTime')"
            prop="createTime"
            align="center"
            header-align="center"
            show-overflow-tooltip
          />
          <el-table-column
            :label="$t('action')"
            header-align="center"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-button
                :disabled="!($route.meta.powers.includes('edit'))"
                size="mini"
                type="primary"
                @click="handleOpenChild(scope)"
              >{{ $t('edit') }}</el-button>
              <el-button
                :disabled="!($route.meta.powers.includes('delete'))"
                size="mini"
                type="danger"
                @click="handleDel(scope)"
              >{{ $t('delete') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!--分页组件-->
      <!-- <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getList"
      /> -->
    </el-card>
    <!-- 弹窗组件 -->
    <deptModel ref="deptModel" @initList="initList"/>
  </div>
</template>

<script>
import crudJob, { getTreeList, doDelete } from '@/api/system/dept'
import deptModel from './module/deptModel'
import mySetting from '@/mixins/mySetting'
import { clearNull } from '@/utils/myTools'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
  name: 'DeptPage',
  components: { deptModel },
  mixins: [mySetting],
  // 数据字典
  data() {
    return {
      multipleSelection: [],
      UpdateDisabled: true,
      DeleteDisabled: true,
      title: '', // 弹窗标题
      form: {},
      infoForm: {},
      searchTags: [
        { label: '关键字', prop: 'name', tag: 'DynInput' }
      ],
      isDisabled: false, // 是否禁用表单内容
      tableData: [],
      tableLoading: true,
      headers: {
        Token: getToken()
      }
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.initList()
  },
  methods: {
    switchHandle(val) {
      switch (val) {
        case 'add':
          this.handleClickAdd()
          break
        case 'download':
          this.download()
          break
        case 'export':
          this.export()
          break
        default:
          break
      }
    },
    // 新增数据
    handleClickAdd() {
      this.$refs.deptModel.handleOpen()
    },
    // 删除数据
    handleDel({ row }) {
      this.$confirm(
        `${this.$t('confirmDeleteData')}?`,
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        doDelete({ id: row.id }).then(res => {
          this.$betterTips(res, this.setOnePage, this.initList)
        })
      })
    },
    addTreeNode() {
      this.$refs.deptModel.handleOpen()
    },
    handleOpenChild({ row }) {
      this.$refs.deptModel.handleOpen(row)
    },
    // 修改数据
    modify() {
      this.$refs.deptModel.handleOpen(this.multipleSelection[0])
    },
    // 初始化列表
    async initList() {
      let obj = {
        ...this.infoForm
      }
      obj = clearNull(obj)
      const res = await getTreeList(obj)
      this.tableData = res.data
      this.total = res.total
      this.tableLoading = false
    },
    // 点击查询
    doSearch() {
      this.initList()
    },
    // 确认新增
    doSave() {
      this.initList()
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    // 关闭弹窗清空数据
    closeDialog() {
      this.isDisabled = false
      this.form = {}
    },
    download() {
      crudJob.download({ name: 'DepartmentList' }).then((res) => {
        window.location.href = this.baseApi + '/' + res.data
      })
    },
    uploadSuccess(response, file, fileList) {
      // 第{ele.index}行 {this.$t(ele.msgCode)}
      // 第{ele.split(',')[0]}行 {this.$t(ele.split(',')[1])}
      // this.netTips(response.code)
      if (response.code !== 1) {
        const h = this.$createElement
        let listVNode
        if (response.data instanceof Array) {
          listVNode = response.data.map((item) => {
            return (
              <p style={ { width: '240px' }}>
                <span style={ { width: '100%', wordWrap: 'break-word' }}>{item.index ? `第{${item.index}}行` : ''}{this.$t(item.msgCode)}</span>
              </p>
            )
          })
          const styles = {
            color: 'teal',
            overflowX: 'hidden',
            overflowY: 'auto',
            width: '280px',
            maxHeight: 'calc(100vh - 120px)'
          }
          this.$notify({
            message: h('div', { style: styles }, listVNode),
            type: 'error',
            duration: 0
          })
        } else {
          this.$betterTips(response)
        }
        fileList = []
      } else {
        this.$betterTips(response, this.initList)
      }
    },
    importFail() {
      this.$notify({
        message: this.$t('uploadFail'),
        type: 'error',
        duration: 3500
      })
    },
    export() {
      let obj = {
        ...this.infoForm
      }
      obj.toexcel = 1
      obj = clearNull(obj)
      crudJob.getList(obj).then((res) => {
        if (res.code === 1) {
          window.location.href = this.baseApi + '/' + res.data
        } else {
          this.doMerge(res)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
.department{
  padding-bottom: 33px;
}
.upload-btn{
  margin: 0 10px;
}
</style>
